const Koa = require('koa')
const Router = require('@koa/router')
const staticFiles = require('koa-static')
const koaFavicon = require('koa-favicon')
const session = require('koa-session')
const ReactSSR = require('react-dom/server')
const koaBody = require('koa-body')

const fs = require('fs')
const path = require('path')

const app = new Koa()
const router = new Router()


const isDev = process.env.NODE_ENV == 'development'

app.use(koaBody())
app.use(koaFavicon(path.join(__dirname, '../favicon.ico')))
app.use(session({
    // key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
    // /** (number || 'session') maxAge in ms (default is 1 days) */
    // /** 'session' will result in a cookie that expires when session/browser is closed */
    // /** Warning: If a session cookie is stolen, this cookie will never expire */
    // maxAge: 86400000,
    // autoCommit: true, /** (boolean) automatically commit headers (default true) */
    // overwrite: true, /** (boolean) can overwrite or not (default true) */
    // httpOnly: true, /** (boolean) httpOnly or not (default true) */
    // signed: true, /** (boolean) signed or not (default true) */
    // rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
    // renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
    // secure: true, /** (boolean) secure cookie*/
}, app))

// app.use('/api/user', require('./util/handle-login'))
// app.use('/api', require('./util/proxy'))
// app.use(async (ctx, next) => {
//     await next()
//     if (ctx.method == 'GET') {
//         console.log('接收到请求-GET')
//         ctx.body = '接收到请求-GET'
//     } else if (ctx.method === 'POST') {
//         console.log('接收到请求-POST')
//         ctx.body = '接收到请求-POST'
//     } else {
//         //其它请求显示404页面
//         console.log('<h1>404!</h1>')
//         ctx.body = '<h1>404!</h1>'
//     }
// })

// const xxx = require('./util/handle-login')
router.post('/api/login', require('./util/handle-login'))
// router.post('/api', async (ctx, next) => {
//     ctx.body = 'xxxx'//ctx.req.query + 'xxx';

//     // xxx(ctx, next)
//     await next()
// })

if (!isDev) {
    const serverEntry = require('../dist/server-entry').default
    const template = fs.readFileSync(path.join(__dirname, "../dist/index.html"), 'utf-8')
    // 静态文件处理
    app.use(staticFiles(path.join(__dirname, '../dist/public')))
    app.use(async (ctx, next) => {
        const appString = ReactSSR.renderToString(serverEntry)
        await next();
        ctx.response.body = template.replace('<app></app>', appString);
    });
} else {
    const devStatic = require('./util/dev-static')
    devStatic(app)
}

// router.get('/api/home/:name', async (ctx, next) => {
//     var name = ctx.params.name
//     ctx.response.body += `<h1>Hello, ${name}!</h1>`;
//     console.log('ctx', ctx)
//     await next()
// })

// router.get('/use/:name', async (ctx, next) => {
//     var name = ctx.params.name
//     ctx.response.body += `<h1>Hello, ${name}!</h1>`;
// })

app.use(router.routes());

app.on('error', err => {
    console.error('server error', err)
});

app.listen(3031)
